<?php
/**
 * FastApp.
 * 3/12/25
 * @Author deepsea
 * @Contact (telegram:deepsea159)
 */

namespace App\Hoenix\Job;

use App\Hoenix\Model\HoenixKeyword;
use App\Hoenix\Model\HoenixKeywordTg;
use Hyperf\AsyncQueue\Job;

class UserKeywordJob extends Job
{

    public function __construct(public string $word, public int $tgId)
    {
    }

    public function handle(): void
    {
        try {
            $cmd = 'python3 ' . dirname(BASE_PATH) . '/py/cut.py ';
            exec($cmd . "'" . $this->word . "'", $output);
            if (empty($output)) return;
            $filtered_words = json_decode($output[0], true);
            $exist = HoenixKeyword::query()->whereIn('kw', $filtered_words)->pluck('kw')->toArray();
            $in = [];
            foreach (array_diff($filtered_words, $exist) as $kw) {
                $in[] = ['kw' => $kw];
            }
            if ($in) HoenixKeyword::query()->insert($in);
            $existId = HoenixKeyword::query()->whereIn('kw', $filtered_words)->pluck('id')->toArray();
            $in = [];
            foreach ($existId as $kid) {
                HoenixKeyword::query()->where(['id' => $kid])->increment('num');
                $in[] = ['kid' => $kid, 'tg_id' => $this->tgId];
            }
            if ($in) HoenixKeywordTg::query()->insert($in);
        } catch (\Throwable $throwable) {
            sys_notify($throwable->getMessage() . $throwable->getTraceAsString());
        }
    }
}